import { NextRequest, NextResponse } from 'next/server'
import { projectQueries, userProjectLinkQueries, userQueries, createAuditLog } from '@/lib/database-prisma'
import { getUserFromRequest } from '@/lib/auth-utils'

// 定义 Project 类型 - 匹配Prisma返回的格式
interface Project {
  id: number;
  name: string;
  description: string;
  createdAt: Date;
}

export async function GET(request: NextRequest) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }
    
    const projects = await projectQueries.getByUserId.all(userInfo.id) as Project[]
    return NextResponse.json(projects)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return NextResponse.json({ error: '获取项目列表失败' }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const body = await request.json()
    const { name, description, memberIds } = body
    
    if (!name || !description) {
      return NextResponse.json({ error: '项目名称和描述不能为空' }, { status: 400 })
    }

    if (name.length > 50) {
      return NextResponse.json({ error: '项目名称不能超过50个字符' }, { status: 400 })
    }

    if (description.length > 300) {
      return NextResponse.json({ error: '项目描述不能超过300个字符' }, { status: 400 })
    }

    // 创建项目
    const projectResult = await projectQueries.create.run(name, description)
    const projectId = projectResult.lastInsertRowid as number

    // 添加创建者到项目成员
    await userProjectLinkQueries.create.run(userInfo.id, projectId)

    // 添加其他成员到项目
    if (memberIds && Array.isArray(memberIds)) {
      for (const memberId of memberIds) {
        if (memberId !== userInfo.id) { // 避免重复添加创建者
          try {
            await userProjectLinkQueries.create.run(memberId, projectId)
          } catch (error) {
            console.warn(`添加成员 ${memberId} 到项目失败:`, error)
            // 继续执行，不中断项目创建
          }
        }
      }
    }

    // 记录审计日志
    await createAuditLog(userInfo.id, {
      type: 'project',
      action: 'create',
      projectId: projectId,
      projectName: name,
      time: new Date().toISOString()
    }, projectId)

    // 返回创建的项目信息
    const newProject = await projectQueries.findById.get(projectId)
    return NextResponse.json(newProject, { status: 201 })
  } catch (error) {
    console.error('创建项目失败:', error)
    return NextResponse.json({ error: '创建项目失败' }, { status: 500 })
  }
} 